package com.gzw.shop.utils;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.gzw.shop.bean.Page;
import com.gzw.shop.http.OkHttpHelper;
import com.gzw.shop.http.SpotsCallBack;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;


/**
 * Created by JACKYGUO on 2017-03-13.
 * 分页工具类
 */

public class Pager {

    private static Builder builder;

    private OkHttpHelper mHelper;

    /**
     * 默认
     */
    private static final int STATE_NORMAL = 0;

    /**
     * 刷新
     */
    private static final int STATE_REFRESH = 1;

    /**
     * 加载更多
     */
    private static final int STATE_MORE = 2;

    private int states = STATE_NORMAL;


    private Pager() {
        mHelper = OkHttpHelper.getInstance();
        initRefreshLayout();
    }

    public void request() {
        requestData();
    }

    public void putParam(String key, Object value) {
        builder.params.put(key, value);
    }


    private void initRefreshLayout() {

        builder.mRefreshLayout.setLoadMore(builder.canLoadMore);
        builder.mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {

                refreshData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {

                if (builder.pageIndex <= builder.totalPage) {
                    loadMoreData();
                } else {
                    Toast.makeText(builder.context, "已经没有更多数据", Toast.LENGTH_SHORT).show();
                    materialRefreshLayout.finishRefreshLoadMore();
                }

            }
        });
    }

    private void refreshData() {
        builder.pageIndex = 1;
        states = STATE_REFRESH;
        requestData();
    }

    private void loadMoreData() {
        builder.pageIndex = ++builder.pageIndex;
        states = STATE_MORE;
        requestData();
    }

    private void requestData() {

        mHelper.get(buliderUrl(), new RequestCallBack(builder.context));
    }


    /**
     * 展示数据,通过接口回调
     *
     * @param datas      数据
     * @param totalPage
     * @param totalCount
     * @param <T>
     */
    private <T> void showData(List<T> datas, int totalPage, int totalCount) {

        switch (states) {

            case STATE_NORMAL:

                if (builder.mPagerListener != null) {
                    builder.mPagerListener.load(datas, totalPage, totalCount);
                }

                break;
            case STATE_REFRESH:
                if (builder.mPagerListener != null) {
                    builder.mPagerListener.refresh(datas, totalPage, totalCount);
                }
                builder.mRefreshLayout.finishRefresh();
                break;

            case STATE_MORE:
                if (builder.mPagerListener != null) {
                    builder.mPagerListener.loadMore(datas, totalPage, totalCount);
                }
                builder.mRefreshLayout.finishRefreshLoadMore();
                break;
        }
    }


    /**
     * 获取URL
     *
     * @return
     */
    private String buliderUrl() {
        return builder.url + "?" + builderParams();
    }

    /**
     * 拼接URL
     * 默认设置curPage  pageSize
     *
     * @return
     */
    private String builderParams() {

        HashMap<String, Object> map = builder.params;

        map.put("curPage", builder.pageIndex);
        map.put("pageSize", builder.pageSize);

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }

        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }


    public static Builder newBuilder() {
        builder = new Builder();
        return builder;
    }

    public static class Builder {

        //变量全部写在Builder里面

        private String url;

        private HashMap<String, Object> params = new HashMap<>();

        private OnPagerListener mPagerListener;

        private Context context;

        private Type type;

        private int totalPage = 1;
        private int pageIndex = 1;
        private int pageSize = 1;

        private boolean canLoadMore;
        private MaterialRefreshLayout mRefreshLayout;

        public Builder setUrl(String url) {
            this.url = url;
            return builder;
        }

        public Builder putParam(String key, Object value) {
            params.put(key, value);
            return builder;
        }

        public Builder setPageSize(int pageSize) {
            this.pageSize = pageSize;
            return builder;
        }

        public Builder setCanLoadMore(boolean canLoadMore) {
            this.canLoadMore = canLoadMore;
            return builder;
        }

        public Builder setRefreshLayout(MaterialRefreshLayout refreshLayout) {
            mRefreshLayout = refreshLayout;
            return builder;
        }

        public Builder setOnPagerListener(OnPagerListener listener) {
            this.mPagerListener = listener;
            return builder;
        }

        public Pager builder(Context context, Type type) {
            this.context = context;
            this.type = type;
            valida();
            return new Pager();
        }

        /**
         * 效验数据
         */
        private void valida() {
            if (context == null) {
                throw new RuntimeException("context can't be null");
            }

            if (TextUtils.isEmpty(this.url)) {
                throw new RuntimeException("url can't be null");
            }

            if (this.mRefreshLayout == null) {
                throw new RuntimeException("RefreshLayout can't be null");
            }
        }
    }


    //用来监听加载数据类型的接口
    public interface OnPagerListener<T> {

        void load(List<T> datas, int totalPage, int totalCount);

        void refresh(List<T> datas, int totalPage, int totalCount);

        void loadMore(List<T> datas, int totalPage, int totalCount);

    }

    class RequestCallBack<T> extends SpotsCallBack<Page<T>> {


        public RequestCallBack(Context context) {
            super(context);
            super.mType = builder.type;
        }

        @Override
        public void onSuccess(Response response, Page<T> tPage) {

            builder.pageIndex = tPage.getCurrentPage();
            builder.totalPage = tPage.getTotalPage();
            showData(tPage.getList(), builder.totalPage, builder.pageIndex);
        }

        @Override
        public void onError(Response response, int code, Exception e) {

        }
    }
}
